# -*- coding: utf-8 -*-
import json
import requests
import os
import signal
import time
import serial
import threading
import base64
import redis
import binascii
import traceback


def signal_handler(signal, frame):

    print('program exit')
    try:
        ser.close()
        gpsfile.close()
    except:
        pass
    exit()
signal.signal(signal.SIGINT, signal_handler)


file = "/home/wwwroot/pavgps/config.json"
global conf

if os.path.isfile(file)==True:

    f=open(file)
    s=f.read()
    conf= json.loads(s)

    for n in conf:
        if type(conf[n])==int:
            continue
        conf[n] = conf[n].strip()

    if ('rtkserver' in conf.keys())==False:
        print('not set rtkserver')
        exit()
    elif ('gpsserver' in conf.keys())==False:
        print('not set gpsserver')
        exit()
    elif conf['gpsserver'].find('zjzd-tech.com')==-1:
        print('gpsserver addr err')
        exit()
    elif ('sid' in conf.keys())==False:
        print('not set sid')
        exit()
    elif ('GpsSerialPort' in conf.keys())==False or conf['GpsSerialPort']=='':
        print('not set GpsSerialPort')
        exit()
    elif ('GpsBaudRate' in conf.keys())==False:
        print('not set GpsBaudRate')
        exit()

    if conf['GpsBaudRate']=='':
        conf['baudRate']=9600


# url = 'http://'+conf['rtkserver']
# res = requests.get(url)
# if res.status_code!=200:
#     print('rtkserver connect err')
# else:
#     print(time.strftime("%Y-%m-%d %H:%M", time.localtime()) ,'rtk sync start...')

def setRtkData(conf):
    ser=None
    while True:
        time.sleep(0.1)
        print('run loop')
        try:
            redis_remote = redis.StrictRedis(host='base.zjzd-tech.com',port=6888,password='zjzd')
            redis_remote.ping()
        except:
             print('reConnect Err')
             pass

        try:
            if ser==None:
                try:
                    ser=serial.Serial(conf['GpsSerialPort'],conf['GpsBaudRate'],timeout=0.5)
                    print( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ,  'gps serail open success')
                except :
                    print('not open gps serialPort')
                    time.sleep(3)
            else:
                # print(ser)
                data = ser.read(1024)
                print(str(binascii.b2a_hex(data)))
                # print(data)
                sdata = base64.b64encode(data)
                conf['redisc'].setex('rtkdata',50,sdata)
                redis_remote.publish('RTK_'+conf['sid'], sdata)

        except Exception as e:
            traceback.print_exc()
            pass


if __name__=='__main__':
    redisc = redis.Redis(host='127.0.0.1',port=6379)
    threads = []
    conf["redisc"]=redisc


    t2 = threading.Thread(target=setRtkData,args=(conf,))
    t2.setDaemon(True)
    t2.start()

    while True:
        # time.sleep(10)
        # rtk_status  = rtkTest(conf)
        # if False==rtk_status:
        #     t2.terminate()
        #     time.sleep(2)

        #     t2 = threading.Thread(target=setRtkData,args=(conf,))
        #     t2.setDaemon(True)
        #     t2.start()
        pass
